package com.prd.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.dto.*;
import com.prd.enums.CustomerContactEnum;
import com.prd.enums.CustomerRemarkEnum;
import com.prd.enums.TypeEnum;
import com.prd.mapper.CustomerMapper;
import com.prd.model.*;
import com.prd.service.*;
import com.prd.tools.CopyNonNullBeanUtils;
import com.prd.tools.DTOUtil;
import com.prd.util.JsonData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户总表 服务实现类
 * </p>
 *
 * @author o1
 * @since 2023-11-03
 */
@Service("CustomerService")
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, CustomerDO> implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Resource(name = "CustomerGuestService")
    private CustomerGuestService guestService;
    @Resource(name = "CustomerContactService")
    private CustomerContactService contactService;
    @Resource(name = "CustomerProjectService")
    private CustomerProjectService projectService;
    @Resource(name = "CustomerRemarkService")
    private CustomerRemarkService remarkService;
    @Resource(name = "CustomerCommRecordService")
    private CustomerCommRecordService recordService;
    @Resource(name = "CustomerTransferHistoryService")
    private CustomerTransferHistoryService transferHistoryService;

    @Override
    public Map<String, Object> getAllCustomer(int page, int size, int customerType, int customerLevel, int customerStatus,
                                              int businessManagerId, int businessDepartmentId, int businessStatus, int status,
                                              String area, Date date) {
        Page<CustomerDO> pageInfo = new Page<>(page, size);
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<CustomerDO>();
        if (customerType != -1)
            wrapper.eq(CustomerDO::getCustomerType, customerType);
        if (customerLevel != -1)
            wrapper.eq(CustomerDO::getCustomerLevel, customerLevel);
        if (customerStatus != -1)
            wrapper.eq(CustomerDO::getCustomerStatus, customerStatus);
        if (businessManagerId != -1)
            wrapper.eq(CustomerDO::getBusinessManagerId, businessManagerId);
        if (businessDepartmentId != -1)
            wrapper.eq(CustomerDO::getBusinessDepartmentId, businessDepartmentId);
        if (businessStatus != -1)
            wrapper.eq(CustomerDO::getBusinessStatus, businessStatus);
        if (status != -1)
            wrapper.eq(CustomerDO::getStatus, status);
        if (area != null)
            wrapper.like(CustomerDO::getCustomerAddress, area);
        if (date != null)
            wrapper.eq(CustomerDO::getCreateTime, date);
        IPage<CustomerDO> customerDOIPage = customerMapper.selectPage(pageInfo, wrapper);
        Map<String, Object> map = new HashMap<>(3);
        map.put("total_record", customerDOIPage.getTotal());
        map.put("total_page", customerDOIPage.getPages());
        map.put("current_data", customerDOIPage.getRecords().stream().map(
                        this::doToDto
                ).collect(Collectors.toList())
        );
        return map;
    }


    @Override
    public JsonData addCustomer(CustomerDTO customerDTO) {
        if (customerDTO.getCompanyName() == null)
            return JsonData.buildError("必须填写公司名称");
//        if (customerDTO.getCustomerName() == null)
//            return JsonData.buildError("必须填写联系人/客人");
//        if (customerDTO.getCustomerPhone() == null)
//            return JsonData.buildError("必须填写联系人/客人的电话");
        if (customerDTO.getBusinessDepartment() == null)
            return JsonData.buildError("必须填写业务部门");
        if (customerDTO.getBusinessManager() == null)
            return JsonData.buildError("必须填写业务负责人");
        customerDTO.setCustomerNo(String.valueOf(customerDTO.hashCode()));
        CustomerDO customerDO = new CustomerDO();
        BeanUtils.copyProperties(customerDTO, customerDO);
        customerMapper.insert(customerDO);
        return JsonData.buildSuccess(customerDO);
    }

    @Override
    public JsonData changeStatus(String customerId, int status) {
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerId);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null)
            return JsonData.buildError("没有对应公司");
        customerDO.setStatus(status);
        customerMapper.update(customerDO, wrapper);
        return JsonData.buildSuccess(customerDO);
    }


    @Override
    public Map<String, Object> queryCustomer(int page, int size, String keyWord) {
        Page<CustomerDO> pageInfo = new Page<>(page, size);
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<CustomerDO>();
        if (keyWord != null) {
            wrapper.like(CustomerDO::getCustomerNo, keyWord);
            wrapper.or().like(CustomerDO::getGuestName, keyWord);
            wrapper.or().like(CustomerDO::getGuestPhone, keyWord);
            wrapper.or().like(CustomerDO::getCompanyName, keyWord);
        }
        IPage<CustomerDO> customerDOIPage = customerMapper.selectPage(pageInfo, wrapper);
        Map<String, Object> map = new HashMap<>(3);
        map.put("total_record", customerDOIPage.getTotal());
        map.put("total_page", customerDOIPage.getPages());
        map.put("current_data", customerDOIPage.getRecords().stream().map(
                        this::doToDto
                ).collect(Collectors.toList())
        );
        return map;
    }


    @Override
    public JsonData updateBusinessManagerInfo(String customer_no, String bus_manager, String bus_department, String bus_phone, int bus_manager_id) {
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        if (bus_manager_id == 0|| bus_department == null || bus_manager == null || bus_phone == null)
            return JsonData.buildError("必须填写相关信息");
        wrapper.eq(CustomerDO::getCustomerNo, customer_no);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null)
            return JsonData.buildError("没有对应公司");
        customerDO.setBusinessPhone(bus_phone);
        customerDO.setBusinessDepartment(bus_department);
        customerDO.setBusinessManager(bus_manager);
        customerDO.setBusinessManagerId(bus_manager_id);
        customerMapper.update(customerDO, wrapper);
        return JsonData.buildSuccess(customerDO);
    }

    @Override
    public JsonData uAddDetail(CustomerDTO customerDTO) {
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        String customerNo = String.valueOf(customerDTO.hashCode());
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        //不存在id
        if (customerDO == null) {
            customerDO = new CustomerDO();
            BeanUtils.copyProperties(customerDTO, customerDO);
            customerDO.setCustomerNo(customerNo);
            customerDO.setCustomerStatus(TypeEnum.Customer.getCode());
            Date nowDate = new Date();
            customerDO.setCreateTime(nowDate);
            customerDO.setIsSimple(2);
            if (customerDTO.getContactList() != null && !customerDTO.getContactList().isEmpty()) {
                if (customerDTO.getContactList().size() > 1)
                    customerDO.setGuestMutiContact(1);
                //填入customer，只存第一位
                CustomerGuestDTO firstContactDTO = customerDTO.getContactList().get(0);
                firstContactDTO.setGuestNo(String.valueOf(firstContactDTO.hashCode()));
                customerDO.setGuestNo(firstContactDTO.getGuestNo());
                customerDO.setGuestName(firstContactDTO.getGuestName());
                customerDO.setGuestPhone(firstContactDTO.getGuestPhone());
                customerDO.setGuestEmail(firstContactDTO.getGuestEmail());
                customerDO.setGuestDepartment(firstContactDTO.getGuestDepartment());
                customerDO.setGuestJob(firstContactDTO.getGuestJob());
                customerDO.setGuestJobLevelId(firstContactDTO.getGuestJobLevelId());
                for (CustomerGuestDTO contactDTO: customerDTO.getContactList()) {
                    contactDTO.setCustomerNo(customerNo);
                    guestService.uAddSimple(contactDTO);
                }
            }
            //所属项目
            if (customerDTO.getProjectList() != null && !customerDTO.getProjectList().isEmpty()) {
                for (CustomerProjectDTO projectDTO: customerDTO.getProjectList()) {
                    projectDTO.setCustomerNo(customerNo);
                    projectService.uAddSimple(projectDTO);
                }
            }
            //客户需求
            if (customerDTO.getCustomerRequireList() != null && !customerDTO.getCustomerRequireList().isEmpty()) {
                for (CustomerRemarkDTO requireDto: customerDTO.getCustomerRequireList()) {
                    requireDto.setType(CustomerRemarkEnum.CustomerRequirementRemark.getCode());
                    requireDto.setNo(customerNo);
                    remarkService.uAdd(requireDto);
                }
            }
            //客户分析
            if (customerDTO.getCustomerAnalyzeList() != null && !customerDTO.getCustomerAnalyzeList().isEmpty()) {
                for (CustomerRemarkDTO requireDto: customerDTO.getCustomerAnalyzeList()) {
                    requireDto.setType(CustomerRemarkEnum.CustomerAnalyze.getCode());
                    requireDto.setNo(customerNo);
                    remarkService.uAdd(requireDto);
                }
            }
            //客户备注
            if (customerDTO.getCustomerRemarkList() != null && !customerDTO.getCustomerRemarkList().isEmpty()) {
                for (CustomerRemarkDTO remarkDto: customerDTO.getCustomerRemarkList()) {
                    remarkDto.setType(CustomerRemarkEnum.CustomerRemark.getCode());
                    remarkDto.setNo(customerNo);
                    remarkService.uAdd(remarkDto);
                }
            }
            //客户来源
            if (customerDTO.getCustomerSourceList() != null && !customerDTO.getCustomerSourceList().isEmpty()) {
                for (CustomerContactDTO customerSource: customerDTO.getCustomerSourceList()) {
                    customerSource.setNo(customerNo);
                    customerSource.setType(CustomerContactEnum.CustomerSource.getCode());
                    contactService.uAdd(customerSource);
                }
            }
            //客户关系人
            if (customerDTO.getCustomerRelevantList() != null && !customerDTO.getCustomerRelevantList().isEmpty()) {
                for (CustomerContactDTO customerRelevant: customerDTO.getCustomerRelevantList()) {
                    customerRelevant.setNo(customerNo);
                    customerRelevant.setType(CustomerContactEnum.CustomerRelevant.getCode());
                    contactService.uAdd(customerRelevant);
                }
            }
            //来往沟通记录
            if (customerDTO.getCustomerCommRecordList() != null && !customerDTO.getCustomerCommRecordList().isEmpty()) {
                for (CustomerCommRecordDTO customerRecord: customerDTO.getCustomerCommRecordList()) {
                    customerRecord.setNo(customerNo);
                    recordService.uAdd(customerRecord);
                }
            }
            customerMapper.insert(customerDO);
            return JsonData.buildSuccess(customerDO);
        }
        else {
            Map<String, Object> map = new HashMap<>(7);
            map.put("businessManagerId", customerDO.getBusinessManagerId());
            map.put("businessManager", customerDO.getBusinessManager());
            map.put("businessDepartment", customerDO.getBusinessDepartment());
            map.put("businessDepartmentId", customerDO.getBusinessDepartmentId());
            map.put("businessPhone", customerDO.getBusinessPhone());
            map.put("createTime", customerDO.getCreateTime());
            map.put("customerNo", customerDO.getCustomerNo());
            return new JsonData(-1, map,"已经报备");
        }
    }

    @Override
    public JsonData uAddSubDetail(CustomerDTO customerDTO) {
        if (customerDTO.getCustomerBossNo() == null)
            return JsonData.buildError("必须填写所归属的客户编号CustomerBossNo");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerDTO.getCustomerBossNo());
        CustomerDO projectDO = customerMapper.selectOne(wrapper);
        if (projectDO == null)
            return JsonData.buildError("未找到所归属的客户");
        return uAddDetail(customerDTO);
    }

    @Override
    public JsonData uUpdateDetail(CustomerDTO customerDTO) {
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerDTO.getCustomerNo());
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            return JsonData.buildError("未查找到对应客户");
        }else {
            CopyNonNullBeanUtils.copyProperties(customerDTO, customerDO);
            customerDO.setCustomerStatus(TypeEnum.Customer.getCode());
            customerDO.setIsSimple(2);
            String customerNo = customerDTO.getCustomerNo();

            List<CustomerGuestDO> guestInDBList = guestService.searchForList(customerNo)
                    .stream().map(DTOUtil::guestDtoToDO).collect(Collectors.toList());
            List<CustomerProjectDO> projectInDBList = projectService.searchForList(customerNo)
                    .stream().map(DTOUtil::projectDtoToDO).collect(Collectors.toList());

            List<CustomerRemarkDO> customerRequireInDBList = remarkService.uSearchForList(customerNo, CustomerRemarkEnum.CustomerRequirementRemark.getCode())
                    .stream().map(DTOUtil::remarkDtoToDO).collect(Collectors.toList());
            List<CustomerRemarkDO> customerAnalyzeInDBList = remarkService.uSearchForList(customerNo, CustomerRemarkEnum.CustomerAnalyze.getCode())
                    .stream().map(DTOUtil::remarkDtoToDO).collect(Collectors.toList());
            List<CustomerRemarkDO> customerRemarkInDBList = remarkService.uSearchForList(customerNo, CustomerRemarkEnum.CustomerRemark.getCode())
                    .stream().map(DTOUtil::remarkDtoToDO).collect(Collectors.toList());
            List<CustomerContactDO> customerContactInDBList = contactService.uSearchForList(customerNo, CustomerContactEnum.CustomerSource.getCode())
                    .stream().map(DTOUtil::contactDtoToDO).collect(Collectors.toList());
            List<CustomerContactDO> customerRelevantInDBList = contactService.uSearchForList(customerNo, CustomerContactEnum.CustomerRelevant.getCode())
                    .stream().map(DTOUtil::contactDtoToDO).collect(Collectors.toList());
            List<CustomerCommRecordDO> customerCommRecordInDBList = recordService.uSearchForList(customerNo)
                    .stream().map(DTOUtil::commRecordDtoToDO).collect(Collectors.toList());

            HashMap<String, Object> otherParam = new HashMap<String, Object>();
            otherParam.put("customerNo", customerNo);

            //客户联系人，即客人
            DTOUtil.compareDBAndDOList(guestInDBList,
                    customerDTO.getContactList().stream().map(DTOUtil::guestDtoToDO).collect(Collectors.toList()),
                    guestService, otherParam);
            if (customerDTO.getContactList() != null && !customerDTO.getContactList().isEmpty()) {
                if (customerDTO.getContactList().size() > 1)
                    customerDO.setGuestMutiContact(1);
                //填入customer，只存第一位
                CustomerGuestDTO firstContactDTO = customerDTO.getContactList().get(0);
                firstContactDTO.setGuestNo(String.valueOf(firstContactDTO.hashCode()));
                firstContactDTO.setCustomerNo(customerNo);
                if (!firstContactDTO.getGuestNo().equals(customerDO.getGuestNo())) {
                    customerDO.setGuestNo(firstContactDTO.getGuestNo());
                    customerDO.setGuestName(firstContactDTO.getGuestName());
                    customerDO.setGuestPhone(firstContactDTO.getGuestPhone());
                    customerDO.setGuestEmail(firstContactDTO.getGuestEmail());
                    customerDO.setGuestDepartment(firstContactDTO.getGuestDepartment());
                    customerDO.setGuestJob(firstContactDTO.getGuestJob());
                    customerDO.setGuestJobLevelId(firstContactDTO.getGuestJobLevelId());
                }
            }
            else {
                customerDO.setGuestNo(null);
                customerDO.setGuestName(null);
                customerDO.setGuestPhone(null);
                customerDO.setGuestEmail(null);
                customerDO.setGuestDepartment(null);
                customerDO.setGuestJob(null);
                customerDO.setGuestJobLevelId(null);
            }

            //所属项目
            DTOUtil.compareDBAndDOList(projectInDBList,
                    customerDTO.getProjectList().stream().map(DTOUtil::projectDtoToDO).collect(Collectors.toList()),
                    projectService, otherParam);

            //客户需求
            otherParam.put("code", CustomerRemarkEnum.CustomerRequirementRemark.getCode());
            DTOUtil.compareDBAndDOList(customerRequireInDBList,
                    customerDTO.getCustomerRequireList().stream().map(DTOUtil::remarkDtoToDO).collect(Collectors.toList()),
                    remarkService, otherParam);

            //客户分析
            otherParam.put("code", CustomerRemarkEnum.CustomerAnalyze.getCode());
            DTOUtil.compareDBAndDOList(customerAnalyzeInDBList,
                    customerDTO.getCustomerAnalyzeList().stream().map(DTOUtil::remarkDtoToDO).collect(Collectors.toList()),
                    remarkService, otherParam);

            //客户备注
            otherParam.put("code", CustomerRemarkEnum.CustomerRemark.getCode());
            DTOUtil.compareDBAndDOList(customerRemarkInDBList,
                    customerDTO.getCustomerRemarkList().stream().map(DTOUtil::remarkDtoToDO).collect(Collectors.toList()),
                    remarkService, otherParam);

            //客户来源
            otherParam.put("code", CustomerContactEnum.CustomerSource.getCode());
            DTOUtil.compareDBAndDOList(customerContactInDBList,
                    customerDTO.getCustomerSourceList().stream().map(DTOUtil::contactDtoToDO).collect(Collectors.toList()),
                    contactService, otherParam);

            //客户关系人
            otherParam.put("code", CustomerContactEnum.CustomerRelevant.getCode());
            DTOUtil.compareDBAndDOList(customerRelevantInDBList,
                    customerDTO.getCustomerRelevantList().stream().map(DTOUtil::contactDtoToDO).collect(Collectors.toList()),
                    contactService, otherParam);

            //来往沟通记录
            DTOUtil.compareDBAndDOList(customerCommRecordInDBList,
                    customerDTO.getCustomerCommRecordList().stream().map(DTOUtil::commRecordDtoToDO).collect(Collectors.toList()),
                    recordService, otherParam);

            CopyNonNullBeanUtils.copyProperties(customerDTO, customerDO);
            customerMapper.update(customerDO, wrapper);
            return JsonData.buildSuccess(customerDO);
        }
    }

    @Override
    public JsonData uInfo(String customerNo) {
        if (customerNo == null)
            return JsonData.buildError("customerNo参数为空");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        CustomerDTO customerDTO = new CustomerDTO();
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }
        BeanUtils.copyProperties(customerDO, customerDTO);
        List<CustomerProjectDTO> projectDTOList = projectService.searchForList(customerNo);
        customerDTO.setProjectList(projectDTOList);
        List<CustomerGuestDTO> contactList = guestService.searchForList(customerNo);
        customerDTO.setContactList(contactList);
        return JsonData.buildSuccess(customerDTO);
    }



    @Override
    public Map<String, Object> uQueryCustomer(int page, int size, String keyWord, int customerType, int customerStatus,
                                              int softOf, int orderBy, String address, int customerLevel,
                                              int businessStatus, int lastBusinessDay) {

        Page<CustomerDO> pageInfo = new Page<>(page, size);
        IPage<CustomerDO> customerDOIPage = customerMapper.selectPage(pageInfo,
                createSearchWrapper(keyWord, customerType, customerStatus, softOf, orderBy, address, customerLevel, businessStatus, lastBusinessDay));
        List<CustomerDTO> customerDTOList = customerDOIPage.getRecords().stream().map(
                this::doToDto
        ).collect(Collectors.toList());
        for (CustomerDTO customerDTO: customerDTOList) {
            if (customerDTO.getCustomerNo() != null) {
                customerDTO.setContactList(guestService.searchForList(customerDTO.getCustomerNo()));
                customerDTO.setProjectList(projectService.searchForList(customerDTO.getCustomerNo()));
            }
            if (customerDTO.getCustomerBossNo() != null) {

            }
        }
        Map<String, Object> map = new HashMap<>(3);
        map.put("total_record", customerDOIPage.getTotal());
        map.put("total_page", customerDOIPage.getPages());
        map.put("current_data", customerDTOList);
        return map;
    }

    @Override
    public List<CustomerDTO> uQueryCustomer2(String keyWord, int customerType, int customerStatus, int softOf, int orderBy, String address, int customerLevel, int businessStatus, int lastBusinessDay) {
        List<CustomerDO> customerDOList = customerMapper.selectList(
                createSearchWrapper(keyWord, customerType, customerStatus, softOf, orderBy, address, customerLevel, businessStatus, lastBusinessDay));
        List<CustomerDTO> customerDTOList = customerDOList.stream().map(this::doToDto).collect(Collectors.toList());
        for (CustomerDTO customerDTO: customerDTOList) {
            if (customerDTO.getCustomerNo() != null) {
                customerDTO.setContactList(guestService.searchForList(customerDTO.getCustomerNo()));
                customerDTO.setProjectList(projectService.searchForList(customerDTO.getCustomerNo()));
            }
        }
        return customerDTOList;
    }

    @Override
    public List<CustomerDTO> uQuerySubCustomer(String bossNo, String customerNo) {
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<CustomerDO>();
        if (bossNo != null && customerNo == null)
            wrapper.eq(CustomerDO::getCustomerBossNo, bossNo);
        else if (bossNo == null && customerNo != null)
            wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        else
            return new ArrayList<>();
        List<CustomerDO> customerDOList = customerMapper.selectList(wrapper);
        List<CustomerDTO> customerDTOList = customerDOList.stream().map(this::doToDto).collect(Collectors.toList());
        for (CustomerDTO customerDTO: customerDTOList) {
            if (customerDTO.getCustomerNo() != null) {
//                customerDTO.setContactList(contactService.searchContactList(customerDTO.getCustomerNo(), -1, 3));
                customerDTO.setProjectList(projectService.searchForList(customerDTO.getCustomerNo()));
            }
        }
        return customerDTOList;

    }


    @Override
    public JsonData uCollect(String customerNo, int isCollect) {
        if (customerNo == null)
            return JsonData.buildError("customerNo参数为空");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }
//        customerDO.setIsCollect(isCollect);
        customerMapper.update(customerDO, wrapper);
        return JsonData.buildSuccess(customerDO);
    }

    @Override
    public JsonData uPinTop(String customerNo, int isPinTop) {
        if (customerNo == null)
            return JsonData.buildError("customerNo参数为空");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }
//        customerDO.setIsPinTop(isPinTop);
        customerMapper.update(customerDO, wrapper);
        return JsonData.buildSuccess(customerDO);
    }

    @Override
    public JsonData uChangeBusinessId(String customerNo, int businessManagerId, String businessManager, int businessDepartmentId, String businessDepartment, String businessPhone) {
        if (customerNo == null)
            return JsonData.buildError("customerNo参数为空");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }
        CustomerTransferHistoryDTO transferHistoryDTO = new CustomerTransferHistoryDTO();
        transferHistoryDTO.setBeforeBusManagerId(customerDO.getBusinessManagerId());
        transferHistoryDTO.setBeforeBusManagerName(customerDO.getBusinessManager());
        transferHistoryDTO.setBeforeBusManagerPhone(customerDO.getBusinessPhone());
        transferHistoryDTO.setAfterBusManagerId(businessManagerId);
        transferHistoryDTO.setAfterBusManagerName(businessManager);
        transferHistoryDTO.setAfterBusManagerPhone(businessPhone);

        customerDO.setBusinessManagerId(businessManagerId);
        customerDO.setBusinessManager(businessManager);
        customerDO.setBusinessDepartmentId(businessDepartmentId);
        customerDO.setBusinessDepartment(businessDepartment);
        customerDO.setBusinessPhone(businessPhone);
        customerMapper.update(customerDO, wrapper);
        transferHistoryService.uAdd(transferHistoryDTO);
        return JsonData.buildSuccess(customerDO);
    }

    @Override
    public Map<String, Object> uCountCustomerType() {
        Map<String, Object> map = new HashMap<>(3);
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        //客户类型: 项目类1，供应链类2，服务类3，渠道类4，消费类5
        int total_record = customerMapper.selectCount(wrapper);
        map.put("total_record", total_record);
        int project_record = customerMapper.selectCount(wrapper.eq(CustomerDO::getCustomerType, 1));
        map.put("project_record", project_record);
        int support_record = customerMapper.selectCount(wrapper.eq(CustomerDO::getCustomerType, 2));
        map.put("support_record", support_record);
        int service_record = customerMapper.selectCount(wrapper.eq(CustomerDO::getCustomerType, 3));
        map.put("service_record", service_record);
        int consumption_record = customerMapper.selectCount(wrapper.eq(CustomerDO::getCustomerType, 5));
        map.put("consumption_record", consumption_record);
        return map;
    }

    @Override
    public JsonData uAddSimple(CustomerDTO customerDTO) {
        String customerNo = String.valueOf(customerDTO.hashCode());
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            customerDO = new CustomerDO();
            CopyNonNullBeanUtils.copyProperties(customerDTO, customerDO);
            customerDO.setCustomerNo(customerNo);
            customerDO.setIsSimple(1);
            CustomerGuestDTO guestDTO = new CustomerGuestDTO();
            guestDTO.setGuestName(customerDTO.getGuestName());
            guestDTO.setGuestPhone(customerDTO.getGuestPhone());
            guestDTO.setGuestJob(customerDTO.getGuestJob());
            guestDTO.setGuestRemark(customerDTO.getGuestRemark());
            guestDTO.setGuestNo(String.valueOf(guestDTO.hashCode()));
            guestDTO.setCustomerNo(customerNo);
            guestService.uAddSimple(guestDTO);
            customerDO.setGuestNo(guestDTO.getGuestNo());

            customerMapper.insert(customerDO);
            //客户来源
            if (customerDTO.getCustomerSourceList() != null && !customerDTO.getCustomerSourceList().isEmpty()) {
                for (CustomerContactDTO customerSource: customerDTO.getCustomerSourceList()) {
                    customerSource.setNo(customerNo);
                    customerSource.setType(CustomerContactEnum.CustomerSource.getCode());
                    contactService.uAdd(customerSource);
                }
            }

            //客户关系人
            if (customerDTO.getCustomerRelevantList() != null && !customerDTO.getCustomerRelevantList().isEmpty()) {
                for (CustomerContactDTO customerRelevant: customerDTO.getCustomerRelevantList()) {
                    customerRelevant.setNo(customerNo);
                    customerRelevant.setType(CustomerContactEnum.CustomerRelevant.getCode());
                    contactService.uAdd(customerRelevant);
                }
            }
            return JsonData.buildSuccess(customerDO);
        }else {
            return new JsonData(-1, customerDO, "已有此客户");
        }
    }

    @Override
    public JsonData uMerge(CustomerDTO customerDTO) {
        String customerNo = String.valueOf(customerDTO.hashCode());
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }else {
            CopyNonNullBeanUtils.copyProperties(customerDTO, customerDO);

            guestService.removeOneByCustomerNo(customerDTO.getCustomerNo());
            CustomerGuestDTO guestDTO = new CustomerGuestDTO();
            guestDTO.setGuestName(customerDTO.getGuestName());
            guestDTO.setGuestPhone(customerDTO.getGuestPhone());
            guestDTO.setGuestJob(customerDTO.getGuestJob());
            guestDTO.setGuestRemark(customerDTO.getGuestRemark());
            guestDTO.setGuestNo(String.valueOf(guestDTO.hashCode()));
            guestDTO.setCustomerNo(customerNo);
            guestService.uAddSimple(guestDTO);
            customerDO.setIsSimple(2);
            customerDO.setGuestNo(guestDTO.getGuestNo());
            customerMapper.update(customerDO, wrapper);

            //客户来源
            if (customerDTO.getCustomerSourceList() != null && !customerDTO.getCustomerSourceList().isEmpty()) {
                for (CustomerContactDTO customerSource: customerDTO.getCustomerSourceList()) {
                    customerSource.setNo(customerNo);
                    customerSource.setType(CustomerContactEnum.CustomerSource.getCode());
                    contactService.uUpdate(customerSource);
                }
            }

            //客户关系人
            if (customerDTO.getCustomerRelevantList() != null && !customerDTO.getCustomerRelevantList().isEmpty()) {
                for (CustomerContactDTO customerRelevant: customerDTO.getCustomerRelevantList()) {
                    customerRelevant.setNo(customerNo);
                    customerRelevant.setType(CustomerContactEnum.CustomerRelevant.getCode());
                    contactService.uUpdate(customerRelevant);
                }
            }
            return JsonData.buildSuccess(customerDO);
        }
    }

    @Override
    public JsonData uRemoveGuestInfo(String customerNo, String guestNo) {
        if (customerNo == null)
            return JsonData.buildError("customerNo参数为空");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }
        //取出最新一位客人进行比较
        if (customerDO.getGuestNo().equals(guestNo)) {
            customerDO.setGuestNo(null);
            customerDO.setGuestName(null);
            customerDO.setGuestEmail(null);
            customerDO.setGuestJob(null);
            customerDO.setGuestJobLevelId(0);
            customerDO.setGuestDepartment(null);
            customerDO.setGuestPhone(null);
            customerDO.setGuestMutiContact(0);
            customerMapper.update(customerDO, wrapper);
        }
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData uInfo2(String customerNo) {
        if (customerNo == null)
            return JsonData.buildError("customerNo参数为空");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        CustomerDTO customerDTO = new CustomerDTO();
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }
        BeanUtils.copyProperties(customerDO, customerDTO);
        List<CustomerProjectDTO> projectDTOList = projectService.searchForList(customerNo);
        customerDTO.setProjectList(projectDTOList);
        List<CustomerGuestDTO> contactList = guestService.searchForList(customerNo);
        customerDTO.setContactList(contactList);

        //客户需求
        customerDTO.setCustomerRequireList(
                remarkService.uSearchForList(customerNo, CustomerRemarkEnum.CustomerRequirementRemark.getCode())
        );
        //客户分析
        customerDTO.setCustomerAnalyzeList(
                remarkService.uSearchForList(customerNo, CustomerRemarkEnum.CustomerAnalyze.getCode())
        );
        //客户备注
        customerDTO.setCustomerRemarkList(
                remarkService.uSearchForList(customerNo, CustomerRemarkEnum.CustomerRemark.getCode())
        );
        //客户来源
        customerDTO.setCustomerSourceList(
                contactService.uSearchForList(customerNo, CustomerContactEnum.CustomerSource.getCode())
        );
        //客户关系人
        customerDTO.setCustomerRelevantList(
                contactService.uSearchForList(customerNo, CustomerContactEnum.CustomerRelevant.getCode())
        );
        //来往沟通记录
        customerDTO.setCustomerCommRecordList(
                recordService.uSearchForList(customerNo)
        );
        return JsonData.buildSuccess(customerDTO);
    }

    @Override
    public JsonData uDeleteSubDetail(String customerBossNo, String customerNo) {
        if (customerNo == null || customerBossNo == null)
            return JsonData.buildError("customerNo/customerBossNo参数为空");
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerDO::getCustomerNo, customerNo);
        CustomerDO customerDO = customerMapper.selectOne(wrapper);
        if (customerDO == null) {
            return JsonData.buildError("查无此客户");
        }
        else {
            customerDO.setCustomerBossNo(null);
            customerMapper.update(customerDO, wrapper);
            return JsonData.buildSuccess(customerDO);
        }
    }

    @Override
    public CustomerDTO getOne(String customerNo) {
        if (customerNo != null) {
            LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CustomerDO::getCustomerNo, customerNo);
            CustomerDO customerDO = customerMapper.selectOne(wrapper);
            if (customerDO != null)
                return doToDto(customerDO);
        }
        return null;
    }


    private Wrapper<CustomerDO> createSearchWrapper(String keyWord, int customerType, int customerStatus,
                                                    int softOf, int orderBy, String address, int customerLevel,
                                                    int businessStatus, int lastBusinessDay) {
        LambdaQueryWrapper<CustomerDO> wrapper = new LambdaQueryWrapper<CustomerDO>();
        if (keyWord != null) {
            wrapper.like(CustomerDO::getGuestName, keyWord);
            wrapper.or().like(CustomerDO::getCompanyName, keyWord);
            wrapper.or().like(CustomerDO::getCustomerNo, keyWord);
            wrapper.or().like(CustomerDO::getGuestPhone, keyWord);
        }

        if (customerType != -1)
            wrapper.eq(CustomerDO::getCustomerType, customerType);
        if (customerStatus != -1)
            wrapper.eq(CustomerDO::getCustomerStatus, customerStatus);
        if (address != null)
            wrapper.like(CustomerDO::getCustomerAddress, address);
        if (customerLevel != -1)
            wrapper.eq(CustomerDO::getCustomerLevel, customerLevel);
        if (businessStatus != -1)
            wrapper.eq(CustomerDO::getBusinessStatus, businessStatus);
        if (lastBusinessDay != -1) {
            Date endDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            calendar.add(Calendar.DAY_OF_MONTH, (-lastBusinessDay + 1));
            Date startDate = calendar.getTime();
            wrapper.ge(CustomerDO::getLastBusinessDay, startDate)
                    .le(CustomerDO::getLastBusinessDay, endDate);
        }

        //排序
        if (softOf != -1 && orderBy != -1) {
            if (orderBy == 1) {
                if (softOf == 1)
                    wrapper.orderByDesc(CustomerDO::getCustomerBenefits);
                if (softOf == 2)
                    wrapper.orderByDesc(CustomerDO::getCreateTime);
//                if (softOf == 3)
//                    wrapper.orderByDesc(CustomerDO::getCustomerBenefits);
            }
            else {
                if (softOf == 1)
                    wrapper.orderByAsc(CustomerDO::getCustomerBenefits);
                if (softOf == 2)
                    wrapper.orderByAsc(CustomerDO::getCreateTime);
//                if (softOf == 3)
//                    wrapper.orderByDesc(CustomerDO::getCustomerBenefits);
            }
        }
//        wrapper.orderByDesc(CustomerDO::getIsPinTop);
        return wrapper;
    }

    private CustomerDO dtoToDo(CustomerDTO customerDTO) {
        CustomerDO customerDO = new CustomerDO();
        BeanUtils.copyProperties(customerDTO, customerDO);
        return customerDO;
    }

    private CustomerDTO doToDto(CustomerDO customerDO) {
        CustomerDTO customerDTO = new CustomerDTO();
        BeanUtils.copyProperties(customerDO, customerDTO);
        return customerDTO;
    }
}
